package com.sskj.motherboard.handler.strategy;

import com.sskj.common.enums.DeviceMessageTypeEnum;
import com.sskj.motherboard.enums.FrameCodeEnum;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class FrameMessageHandlerFactory {

    private final Map<Integer, IFrameMessageHandlerStrategy> handlerFactoryMap = new ConcurrentHashMap<>();

    @Autowired
    private List<IFrameMessageHandlerStrategy> frameMessageHandlerStrategies;

    // 注册
    public void register(Integer commandCode, IFrameMessageHandlerStrategy frameMessageHandlerStrategy) {
        handlerFactoryMap.putIfAbsent(commandCode, frameMessageHandlerStrategy);
    }

    // 获取
    public IFrameMessageHandlerStrategy getHandler(Integer commandCode) {
        return handlerFactoryMap.get(commandCode);
    }

    @PostConstruct
    public void init() {
        frameMessageHandlerStrategies.forEach(strategyHandler -> {
            if (strategyHandler instanceof RegisterHandler) {
                register(DeviceMessageTypeEnum.REGISTER.getType(), strategyHandler);
            } else if (strategyHandler instanceof HeartbeatHandler) {
                register(DeviceMessageTypeEnum.HEARTBEAT_CHECK.getType(), strategyHandler);
            } else if (strategyHandler instanceof OfflineMessageHandler) {
                register(DeviceMessageTypeEnum.OFFLINE.getType(), strategyHandler);
            }
        });
    }
}
